/**create by liuhua at 2020年10月22日 下午4:41:24**/
package com.star.aries.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mathworks.toolbox.javabuilder.MWException;
import com.star.aries.constant.ErrorCodeEnum;
import com.star.aries.dao.TrainTypeDao;
import com.star.aries.domain.TrainType;
import com.star.aries.dto.req.TrainTypeSaveRequestDto;
import com.star.aries.dto.req.TrainTypeUpdateRequestDto;
import com.star.aries.dto.res.TrainTypeListResponseDto;
import com.star.aries.exception.HnServiceException;

@Service
public class TrainTypeService {
  @Autowired
  private TrainTypeDao trainTypeDao;
  
  public List<TrainTypeListResponseDto> listTrainType() throws IOException, MWException {
    List<TrainType> list = trainTypeDao.listTrainType();
    if(null == list) {
      return new ArrayList<>();
    }
    return list.stream().map(t -> {
      return TrainTypeListResponseDto.builder().trainTypeId(t.getTrainTypeId()).name(t.getName()).build();
    }).collect(Collectors.toList());
  }

  public String addTrainType(TrainTypeSaveRequestDto saveDto) throws IOException {
    List<TrainType> types = this.trainTypeDao.listTrainTypeByName(saveDto.getName());
    if(types.size() > 0) {
      throw new HnServiceException(ErrorCodeEnum.PARAM_ERROR, "名称已存在");  
    }
    TrainType save = new TrainType();
    save.setName(saveDto.getName());
    trainTypeDao.addTrainType(save);
    return "类型添加成功，请开打文件夹并放入Excel文件(structure parameters.xlsx, acousticCav parameters.xlsx, adjacent area.xlsx, powerinput.xlsx, tlforyears.xlsx, transmissionloss.xlsx)";
  }

  public void updateTrainType(TrainTypeUpdateRequestDto updateDto) throws IOException {
    TrainType old = this.trainTypeDao.getTrainType(updateDto.getTrainTypeId());
    if(null == old) {
      throw new HnServiceException(ErrorCodeEnum.PARAM_ERROR, "记录不存在");
    }
    TrainType update = new TrainType();
    update.setTrainTypeId(updateDto.getTrainTypeId());
    update.setName(updateDto.getName());
    update.setExcelPath(old.getExcelPath());
    if(! old.getName().equalsIgnoreCase(updateDto.getName())) {
      List<TrainType> types = this.trainTypeDao.listTrainTypeByName(updateDto.getName());
      if(types.size() > 0) {
        throw new HnServiceException(ErrorCodeEnum.PARAM_ERROR, "名称已存在");  
      }
    }
    trainTypeDao.updateTrainType(update);
  }

  public void deleteTrainType(Long trainTypeId) throws IOException {
    trainTypeDao.deleteTrainType(trainTypeId);
  }

  public void openFolder(Long trainTypeId) throws IOException {
    TrainType type = trainTypeDao.getTrainType(trainTypeId);
    if(null == type) {
      throw new HnServiceException(ErrorCodeEnum.PARAM_ERROR, "记录不存在");
    }
    Runtime.getRuntime().exec("cmd.exe /c explorer " + type.getExcelPath());
  }
}
